package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.domain.model.LoginAppUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.system.service.IAppUserService;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class AppLoginService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private AppTokenService appTokenService;
    @Resource
    private IAppUserService appUserSevice;


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password) {
        AppUser appUser = appUserSevice.selectAppUserByUserName(username);
        if (appUser == null) {
            throw new ServiceException("用户不存在");
        }
        if (!appUserSevice.checkPassword(password, appUser.getSalt(), appUser.getPasswordHash())) {
            throw new ServiceException("密码不正确");
        }
        LoginAppUser loginAppUser = new LoginAppUser(appUser.getId(), appUser);
        // 生成token
        return appTokenService.createAppToken(loginAppUser);
    }

}
